<template>
	<div class="search-select">
		<div class="select-box w100 flex flexL flex-warp ovh">
			<div class="select-item" v-for="item,index in selectList" :key="index">
				{{ item.name }}
				<div class="select-del" @click="delItem(index)" v-if="!showMode">
					<el-icon size="12px"><Minus /></el-icon>
				</div>
			</div>
			<div class="select-add" @click="addItem" v-if="!showMode">
				<el-icon><Plus /></el-icon>
			</div>
		</div>
		<el-dialog v-model="visible" :title="dialogTitle" :width="dialogWidth" center :destroy-on-close="true" custom-class="custom-class-one">
			<template #header>
				<div class="my-header">
					<div class="add">
						<el-button type="primary" @click="addNew">
							{{ $t('add') }} <el-icon><Plus /></el-icon>
						</el-button>
					</div>
					{{ dialogTitle }}
				</div>
			</template>
			<div>
				<el-input v-model="searchValue" @input="searchInput" :placeholder="placeholder" :prefix-icon="Search" clearable/>
			</div>
			<div v-show="showAddInput" class="mt10">
				<el-input v-model="addValue" :placeholder="$t('Enter')" ref="addInputRef" @submit.native.prevent @keyup.enter="addConfirm()">
					<template #append>
						<el-button @click="addConfirm" :disabled="dataloading">{{ $t('Save') }}</el-button>
					</template>
				</el-input>
			</div>
			<el-scrollbar ref="elScrollbarRef" v-loading="dataloading" height="300px">
				<div class="search-list mt10">
					<div class="search-item" v-for="item,index in searchDataList" :key="index">
						<el-checkbox v-model="item.checked" label="" @change="checkboxChange(item, $event)">
							<template #default>
								<div class="search-label">{{ item.name }}</div>
							</template>
						</el-checkbox>
					</div>
					<div class="c999 flex flexC flexL" style="height: 250px;" v-if="searchDataList.length == 0">{{ $t('nodata') }}</div>
				</div>
			</el-scrollbar>
			<div class="w100 flex flexC mt10">
				<el-button type="primary" @click="submitHandle()" :disabled="dataloading">{{ $t('Save') }}</el-button>
			</div>
		</el-dialog>
		<!-- 新增联系人 -->
		<add-contact ref="addContactRef" @refreshDataList="addEnd($event)"></add-contact>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { postApi } from '@/api/api'
import { ElMessage } from 'element-plus/es'
import {
  Plus,
  Minus,
	Search
} from '@element-plus/icons-vue'
import AddContact from '@/views/PageContacts/add-or-update.vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const props = defineProps({
	modelValue: { // 双向绑定
		type: [String, Array],
		required: true
	},
	placeholder: { // 搜索框提示语
		type: String,
		default: 'Search'
	},
	dialogWidth: { // 弹窗默认宽度
		type: String,
		default: '500px'
	},
	dialogTitle: { // 弹窗标题
		type: String,
		default: 'select'
	},
	dataUrl: { // 数据列表加载接口
		type: String,
		default: ''
	},
	dataPageUrl: { // 数据列表加载接口(带分页查询)
		type: String,
		default: ''
	},
	addUrl: { // 当前页面新增数据接口
		type: String,
		default: ''
	},
	isId: { // 是否ID关联
		type: Boolean,
		default: false
	},
	showMode: { // 查看模式
		type: Boolean,
		default: false
	},
	nameProp: { // 页面展示属性名称
		type: String,
		default: 'name'
	},
	addType: { // 自定义添加规则
		type: String,
		default: ''
	},
})
const emit = defineEmits(['update:modelValue'])

const visible = ref(false)
const btnloading = ref(false)
const dataloading = ref(false)
const dataList = ref([]) // 初始化页面加载全部数据
const searchDataList: any = ref([]) // 新增搜索时的备选数据
const selectList: any = ref([]) // 已选数据（展示）
const selectListEd: any = ref([]) // 已选数据（选中）
const addContactRef = ref() // 添加联系人组件
const addInputRef = ref() // 添加输入框组件
const elScrollbarRef = ref() // 滚动区域组件
// 搜索字段
const searchValue = ref('')
// 显示新增输入框
const showAddInput = ref(false)
// 新增字段
const addValue = ref('')

// 新增条目
const addNew = () => {
	if (props.addType == 'contact') {
		addContactRef.value.init({})
	} else {
		addValue.value = ''
		showAddInput.value = true
		nextTick(() => {
			addInputRef.value.focus()
		})
	}
}

// 输入框确定输入并添加
const addConfirm = () => {
	// 此处需要调接口保存内容 - addUrl
	if (addValue.value) {
		dataloading.value = true
		const ajaxData: any = {}
		if (props.addType == 'tag') {
			ajaxData.tag_name = addValue.value
		}
		postApi(props.addUrl,ajaxData,'').then((res: any) => {
			dataloading.value = false
			showAddInput.value = false
			if(res.code == 200){
				console.log(res);
				addEnd(addValue.value)
			} else {
				ElMessage.error(res.message || res.data || t('opaError'))
			}
		}).catch((err: any) => {
			dataloading.value = false
			showAddInput.value = false
			console.log(err)
		})
	}
}

// 新增后的事件处理
const addEnd = (e: any) => {
	dataloading.value = true
	const ajaxData: any = {
		page: 1,
		size: 1,
	}
	if (props.addType == 'contact') {
		ajaxData.key_word = e
	} else if (props.addType == 'tag') {
		ajaxData.tag_name = e
	}
	postApi(props.dataPageUrl,ajaxData,'').then((res: any) => {
		dataloading.value = false
		if(res.code == 200){
			console.log(res);
			if (res.data.data.length) {
				const addOne = res.data.data.map((i: any) => {
					return {
						...i,
						checked: true,
						id: i.id,
						name: `${i[props.nameProp]}` // （${i.currency_symbol}）
					}
				})
				searchDataList.value.unshift(addOne[0])
				selectListEd.value.unshift(addOne[0])
				nextTick(() => {
					elScrollbarRef.value.setScrollTop(0)
				})
			}
		} else {
			ElMessage.error(res.message || res.data || t('opaError'))
		}
	}).catch((err: any) => {
		dataloading.value = false
		console.log(err)
	})
}

// 添加
const addItem = () => {
	searchValue.value = ''
	addValue.value = ''
	showAddInput.value = false
	getDataList()
	visible.value = true
}

// 删除
const delItem = (i: any) => {
	selectList.value.splice(i, 1)
	updateEmit()
}

// 保存提交
const submitHandle = () => {
	// const list1 = JSON.parse(JSON.stringify(selectList.value))
	// searchDataList.value.forEach((i: any) => {
	// 	if (i.checked) {
	// 		if (props.isId) {
	// 			if (!list1.some((em: any) => em.id == i.id)) {
	// 				list1.push({
	// 					id: i.id,
	// 					name: i.name
	// 				})
	// 			}
	// 		} else {
	// 			if (!list1.some((em: any) => em.name == i.name)) {
	// 				list1.push({
	// 					id: i.id,
	// 					name: i.name
	// 				})
	// 			}
	// 		}
	// 	}
	// });
	selectList.value = selectListEd.value.map(i => {
		return {
			id: i.id,
			name: i.name || i.tag_name
		}
	})
	updateEmit()
	visible.value = false
}

// 绑定更新
const updateEmit = () => {
	console.log(selectList.value)
	if (props.isId) {
		emit('update:modelValue', selectList.value.map((i: any) => i.id))
	} else {
		emit('update:modelValue', selectList.value.map((i: any) => i.name))
	}
}

let timer: any = null
// 搜索框变动
const searchInput = (e: any) => {
	console.log(e)
	clearTimeout(timer)
	timer = setTimeout(() => {
		getDataList(e)
	}, 180)
}

// 获取下拉列表
const getDataList = (key_word: any = '') => {
	dataloading.value = true
	const ajaxData: any = {
		page: 1,
		size: 30,
	}
	if (props.addType == 'contact') {
		ajaxData.key_word = key_word
	} else if (props.addType == 'tag') {
		ajaxData.tag_name = key_word
	}
	if (props.dataPageUrl) {
		postApi(props.dataPageUrl, ajaxData, '').then((res: any) => {
			dataloading.value = false
			if(res.code == 200){
				console.log(res);
				searchDataList.value = res.data.data.map((i: any) => {
					return {
						...i,
						checked: selectListEd.value.some((em: any) => em.id ==i.id),
						id: i.id,
						name: `${i[props.nameProp]}` // （${i.currency_symbol}）
					}
				})
			} else {
				ElMessage.error(res.message || res.data || t('opaError'))
			}
		}).catch((err: any) => {
			dataloading.value = false
			console.log(err)
		})
	} else {
		setTimeout(() => {
			dataloading.value = false
		}, 300);
	}
}
const checkboxChange = (item: any, e: any) => {
	console.log(item, e);
	if (e) {
		selectListEd.value.push(item)
	} else {
		const itemNdex = selectListEd.value.findIndex(i => i.id == item.id)
		if (itemNdex != -1) {
			selectListEd.value.splice(itemNdex, 1)
		}
	}
}
onMounted(() => {
	// console.log('SearchSelect组件加载', props.modelValue)
	const firstList: any = props.modelValue
	const selectListShow: any = []
	if (props.dataUrl) {
		// 加载数据列表
		postApi(props.dataUrl,{},'').then((res: any) => {
			if(res.code == 200){
				console.log(res);
				if (res.data) {
					dataList.value = res.data.map((i: any) => {
						if (props.isId) {
							if (firstList.some((em: any) => em == i.id)) {
								selectListShow.push({
									id: i.id,
									name: i[props.nameProp]
								})
							}
						} else {
							if (firstList.some((em: any) => em == i[props.nameProp])) {
								selectListShow.push({
									id: i.id,
									name: i[props.nameProp]
								})
							}
						}
						return {
							...i,
							id: i.id,
							name: `${i[props.nameProp]}` // （${i.currency_symbol}）
						}
					})
					selectListEd.value = JSON.parse(JSON.stringify(selectListShow))
					selectList.value = selectListShow
					console.log('初始化加载已选数据', selectList.value)
				}
			} else {
				ElMessage.error(res.message || res.data || t('opaError'))
			}
		}).catch((err: any) => {
			console.log(err)
		})
	}
})
</script>

<style lang="scss" scoped>
.search-select{
	width: 100%;
	.select-box{
		.select-item{
			position: relative;
			height: 24px;
			line-height: 24px;
			border-radius: 12px;
			padding: 0 10px;
			border: 1px solid #FF9D1A;
			color: #FF9D1A;
			box-sizing: border-box;
			margin-right: 30px;
			margin-top: 5px;
			.select-del{
				position: absolute;
				top: -5px;
				right: -20px;
				width: 16px;
				height: 16px;
				border-radius: 8px;
				display: flex;
				justify-content: center;
				align-items: center;
				border: 1px solid #C6C6C6;
				color: #C6C6C6;
				cursor: pointer;
				box-sizing: border-box;
				font-size: 12px;
			}
		}
		.select-add{
			width: 24px;
			height: 24px;
			border-radius: 12px;
			display: flex;
			justify-content: center;
			align-items: center;
			border: 1px solid #FF9D1A;
			color: #FF9D1A;
			cursor: pointer;
			margin-top: 5px;
			box-sizing: border-box;
		}
	}
	.my-header{
		font-size: 18px;
		position: relative;
		.add{
			position: absolute;
			top: 0;
			left: 0;
			color: #fff;
		}
	}
	.search-list{
		width: 100%;
		// height: 300px;
		// overflow-y: auto;
		.search-item{
			width: 100%;
			height: 40px;
			display: flex;
			align-items: center;
			.search-label{
				height: 40px;
				width: 419px;
				border-bottom: 1px solid #ddd;
				display: flex;
				align-items: center;
				margin-left: 5px;
			}
		}
	}
	.el-form-item .el-form-item{
		margin-bottom: 18px;
	}
	:deep(){
		.el-dialog__body{
			padding-top: 10px;
		}
	}
}
</style>
